package cn.agiledata.bank.myspace.action;

import java.awt.Image;
import java.io.InputStream;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import cn.agiledata.bank.account.dao.hibernate.HibernateAccountDAO;
import cn.agiledata.bank.account.service.IReturnCodeHolder;
import cn.agiledata.bank.audit.exception.AuditException;
import cn.agiledata.bank.common.dao.AccountTemplateInter;
import cn.agiledata.bank.common.servlet.InitForString;
import cn.agiledata.bank.common.util.Constant;
import cn.agiledata.bank.common.util.StringUtil;
import cn.agiledata.bank.common.util.WeatherUtil;
import cn.agiledata.bank.hibernateBean.Account;
import cn.agiledata.bank.hibernateBean.AccountBank;
import cn.agiledata.bank.hibernateBean.BankInfo;
import cn.agiledata.bank.hibernateBean.CityInfo;
import cn.agiledata.bank.myspace.form.IdcardAuthenticateForm;
import cn.agiledata.bank.myspace.form.MyAccountBankForm;
import cn.agiledata.bank.myspace.service.AuthenticateService;
import cn.agiledata.bank.myspace.service.IMySpaceService;
import com.vnv.infrastructure.action.IPBBaseAction;
import com.vnv.infrastructure.exception.IPBAppException;
import com.vnv.infrastructure.exception.IPBException;
import com.vnv.infrastructure.logic.IPBAppFactory;

public class AuthenticateAction extends IPBBaseAction {
	private AccountTemplateInter getAccounteTemplate() {
		return (AccountTemplateInter) IPBAppFactory.getObj("accountTemplate");
	}

	private AuthenticateService getAuthenticateService() {
		return (AuthenticateService) IPBAppFactory
				.getObj("authenticateService");
	}

	protected IMySpaceService getMySpaceService() throws IPBException {
		return (IMySpaceService) IPBAppFactory.getObj(IMySpaceService.MGR_ID);
	}

	private void setErrorMessage(HttpServletRequest request, String message) {
		request.getSession().setAttribute("message", message);
	}

	protected ActionForward getAppExceptionForward(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response, IPBAppException e) {
		ActionForward forward = super.getAppExceptionForward(mapping,
				actionForm, request, response, e);
		if (e instanceof AuditException) {
			request.setAttribute("bundle", "audit");
		}
		return forward;
	}

	private Account getCurrentAccount(HttpServletRequest request) {
		long accountId = WeatherUtil.getAccountIdFromSession(request);
		return getAccounteTemplate().getAccount(String.valueOf(accountId));
	}

	public ActionForward preSubmitIdcard(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		List provinceList = (List) InitForString.dataDictMap
				.get("PROVINCE_INFO");
		request.setAttribute("province", provinceList);
		List cityList = null;
		cityList = (List) InitForString.dataDictMap
				.get(((CityInfo) provinceList.get(0)).getCityId());
		request.setAttribute("city", cityList);
		if (cityList == null) {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
			request.setAttribute("city", cityList);
		}
		saveToken(request);
		return mapping.findForward("success");
	}

	public ActionForward submitIdcard(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		IdcardAuthenticateForm form = (IdcardAuthenticateForm) actionForm;
		String idcardName = form.getIdcardName();// 真实姓名
		String idcardNo = form.getIdcardNo(); // 身份证卡号
		String submitMethod = form.getSubmitMethod(); // 提交方式 身份证还是传真
		FormFile idcardPhoto = form.getIdcardPhoto(); // 正面图片
		FormFile backOfIdcardPhoto = form.getBackOfIdcardPhoto();// 背面图片
		Account account = getCurrentAccount(request);
		BankInfo bi = getMySpaceService().getBankInfo(form.getBankInfoId());

		AccountBank ab = null;
		form.setBankAlias(form.getIdcardName());
		IMySpaceService mssi = (IMySpaceService) getMySpaceService();
		ab = new AccountBank();
		BeanUtils.copyProperties(ab, form);

		// 检查银行卡号码和别名是否唯一
		if (mssi.isUniqueAccountBank(ab.getAccountId(), account.getId(), null)
				&& mssi.isUniqueAccountAlias(ab.getBankAlias(),
						account.getId(), null)) {
			ab.setId(null);
			ab.setIsValid("Y");
			ab.setCreateUser(account.getAccountId());
			ab.setCreateTime(new Date());
			ab.setUpdateUser(account.getAccountId());
			ab.setUpdateTime(new Date());
			ab.setAccountName(form.getIdcardName());

			if (account.getAccountBanks().size() == 0) {
				ab.setDefaultFlag("Y");
			} else {
				boolean flag = false;
				Set accountBanks = account.getAccountBanks();
				for (Iterator it = accountBanks.iterator(); it.hasNext();) {
					AccountBank tempAb = (AccountBank) it.next();
					if ("Y".equals(tempAb.getIsValid())
							&& "Y".equals(tempAb.getDefaultFlag())) {// 有默认并且没有删除
						flag = true;
					}
				}
				if (flag) {
					ab.setDefaultFlag("N");
				} else {
					ab.setDefaultFlag("Y");
				}
			}
		} else {
			setErrorMessage(request, "accountBankIDDuplicated");
			return mapping.findForward("failure");
		}

		ab.setBankInfo(bi);
		ab.setAccount(account);
		if (!StringUtil.isIdcardNo(idcardNo)) {// 身份证号码格式错误
			setErrorMessage(request, "idcard_format_error");
			return mapping.findForward("failure");
		} else if (!getAuthenticateService().authenticatableIdcardNo(account,
				idcardNo)) {// 身份证号码已被别人使用
			setErrorMessage(request, "idcard_number_used");
			return mapping.findForward("failure");
		} else if (Constant.AUTHENTICATION_METHOD_IDCARD_UPLOAD
				.equals(submitMethod)) {// 上传身份证扫描图片
			if (idcardPhoto == null || idcardPhoto.getFileSize() == 0) {// 身份证正面图片为空
				setErrorMessage(request, "idcard_photo_empty");
				return mapping.findForward("failure");
			} else if (idcardPhoto.getFileSize() > Constant.FILESIZE_512K) {// 身份证正面图片数据太大
				setErrorMessage(request, "idcard_photo_over_512KB");
				return mapping.findForward("failure");
			}else if (!idcardPhoto.getFileName().endsWith("gif")
					&& !idcardPhoto.getFileName().endsWith("jpg")
					&& !idcardPhoto.getFileName().endsWith("jpeg")) {// 身份证图片类型
				setErrorMessage(request, "idcard_photo_format_error");
				return mapping.findForward("failure");
			} else {// 身份证正面图片不为空且数据大小没有超出范围
				InputStream idcardPhotoStream = idcardPhoto.getInputStream();
				Image image = ImageIO.read(idcardPhotoStream);
				idcardPhotoStream.close();
				if (image == null) {
					setErrorMessage(request, "idcard_photo_format_error");
					return mapping.findForward("failure");
				}

				if (backOfIdcardPhoto == null
						|| backOfIdcardPhoto.getFileSize() == 0) {// 身份证背面图片为空
					// 保存一代身份证图片
					idcardPhotoStream = idcardPhoto.getInputStream();
					if (getAuthenticateService().submitIdcard(account,
							idcardName, idcardNo, submitMethod,
							idcardPhotoStream, null)) {
						if (isTokenValid(request, true)) {
							mssi.updateAccountBank(ab);
						}
						return mapping.findForward("success");
					} else {
						setErrorMessage(request,
								"idcard_authentication_no_valid_rule");
						return mapping.findForward("failure");
					}
				} else {// 身份证背面图片不为空
					if (backOfIdcardPhoto.getFileSize() > Constant.FILESIZE_512K) {// 身份证背面图片数据太大
						setErrorMessage(request, "idcard_photo_back_over_512KB");
						return mapping.findForward("failure");
					} else if (!backOfIdcardPhoto.getFileName().endsWith("gif")
							&& !backOfIdcardPhoto.getFileName().endsWith("jpg")
							&& !backOfIdcardPhoto.getFileName().endsWith("jpeg")) {// 身份证图片类型
						setErrorMessage(request, "idcard_photo_format_error");
						return mapping.findForward("failure");
					} else {
						InputStream idcardPhotoBackStream = backOfIdcardPhoto
								.getInputStream();
						Image imageBack = ImageIO.read(idcardPhotoBackStream);
						idcardPhotoBackStream.close();
						if (imageBack == null) {
							setErrorMessage(request,
									"idcard_photo_format_error");
							return mapping.findForward("failure");
						}

						// 保存二代身份证
						idcardPhotoStream = idcardPhoto.getInputStream();
						idcardPhotoBackStream = backOfIdcardPhoto
								.getInputStream();
						if (getAuthenticateService().submitIdcard(account,
								idcardName, idcardNo, submitMethod,
								idcardPhotoStream, idcardPhotoBackStream)) {
							if (isTokenValid(request, true)) {
								mssi.updateAccountBank(ab);
							}
							return mapping.findForward("success");
						} else {
							setErrorMessage(request,
									"idcard_authentication_no_valid_rule");
							return mapping.findForward("failure");
						}
					}
				}
			}
		}

		// 传真身份证复印件
		if (getAuthenticateService().submitIdcard(account, idcardName,
				idcardNo, submitMethod, null, null)) {
			if (isTokenValid(request, true)) {
				mssi.updateAccountBank(ab);
			}
			return mapping.findForward("success");
		}

		setErrorMessage(request, "idcard_authentication_no_valid_rule");
		return mapping.findForward("failure");
	}

	public ActionForward toClearAccount(ActionMapping mapping,
			ActionForm actionForm, HttpServletRequest request,
			HttpServletResponse response) throws IPBException, Exception {
		List provinceList = (List) InitForString.dataDictMap
				.get("PROVINCE_INFO");
		request.setAttribute("province", provinceList);
		List cityList = null;
		cityList = (List) InitForString.dataDictMap
				.get(((CityInfo) provinceList.get(0)).getCityId());
		request.setAttribute("city", cityList);
		if (cityList == null) {
			cityList = (List) InitForString.dataDictMap
					.get(((CityInfo) provinceList.get(0)).getCityId());
			request.setAttribute("city", cityList);
		}
		saveToken(request);
		return mapping.findForward("success");
	}
	
	public ActionForward clearAccount(ActionMapping mapping,
	ActionForm actionForm, HttpServletRequest request,
	HttpServletResponse response) throws IPBException, Exception {
		IdcardAuthenticateForm form = (IdcardAuthenticateForm) actionForm;
		Account account = getCurrentAccount(request);
		BankInfo bi = getMySpaceService().getBankInfo(form.getBankInfoId());
		AccountBank ab = null;
		form.setBankAlias(form.getIdcardName());
		IMySpaceService mssi = (IMySpaceService) getMySpaceService();
		account.getAccountCompany().setLinkMan(form.getLinkMan());
		account.getAccountCompany().setLinkTel(form.getLinkTel());
		ab = new AccountBank();
		BeanUtils.copyProperties(ab, form);
		// 检查银行卡号码和别名是否唯一
		if (mssi.isUniqueAccountBank(ab.getAccountId(), account.getId(), null)
				&& mssi.isUniqueAccountAlias(ab.getBankAlias(),
						account.getId(), null)) {
			ab.setId(null);
			ab.setIsValid("Y");
			ab.setCreateUser(account.getAccountId());
			ab.setCreateTime(new Date());
			ab.setUpdateUser(account.getAccountId());
			ab.setUpdateTime(new Date());
			ab.setAccountName(form.getIdcardName());
			
			if (account.getAccountBanks().size() == 0) {
				ab.setDefaultFlag("Y");
			} else {
				boolean flag = false;
				Set accountBanks = account.getAccountBanks();
				for (Iterator it = accountBanks.iterator(); it.hasNext();) {
					AccountBank tempAb = (AccountBank) it.next();
					if ("Y".equals(tempAb.getIsValid())
							&& "Y".equals(tempAb.getDefaultFlag())) {// 有默认并且没有删除
						flag = true;
					}
				}
				if (flag) {
					ab.setDefaultFlag("N");
				} else {
					ab.setDefaultFlag("Y");
				}
			}
		} else {
			setErrorMessage(request, "accountBankIDDuplicated");
			return mapping.findForward("failure");
		}
		
		ab.setBankInfo(bi);
		ab.setAccount(account);
		if (getAuthenticateService().submitClearAmount(account, "3A")) {
				mssi.updateAccountBank(ab);
			return mapping.findForward("success");
		} else {
			setErrorMessage(request,
					"clearamount_authentication_no_valid_rule");
			return mapping.findForward("failure");
		}
	}
}
